package com.pic.others.config.minio;


import cn.hutool.core.io.unit.DataSizeUtil;
import cn.hutool.core.io.unit.DataUnit;
import com.pic.common.utils.DateUtils;
import io.minio.*;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
 
@Component
@EnableConfigurationProperties(MinIOConfigProperties.class)
@Slf4j
public class MinIOUtil {
 
    @Autowired
    private MinIOConfigProperties minIOConfigProperties;
 
    @Autowired
    private MinioClient minioClient;
 
    private final static String separator = "/";




    /**
     * 判断文件是否存在
     * @param bucketName
     * @return
     */
    public boolean existBucket(String bucketName, String objectName){
        // 若数据库中存在，根据数据库中的文件信息，则继续判断bucket中是否存在
        try {
            InputStream inputStream = minioClient.getObject(GetObjectArgs
                    .builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .build());
            if (inputStream == null) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }
    /**
     * 判断bucket是否存在，不存在则创建, 默认为yml配置的 bucket
     */
    public String existBucket(String bucketName){
        if (StringUtils.isBlank(bucketName)) {
            bucketName = minIOConfigProperties.getBucket();
        }
        try {
            boolean exist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if(!exist){
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
        }catch (Exception e){
            log.error("minio exist Bucket error.",e);
            throw new RuntimeException("判断bucket是否存在，不存在则创建,失败");
        }
        return bucketName;
    }

    /**
     * 获取图片的大小
     * @param bucketName
     * @param locate
     * @return
     * @throws Exception
     */
    public String getPictureSize(String bucketName,String locate) throws Exception{
        log.info("我发现的locate:"+locate);
        try{
            String prefix="/picmemo";
            // 定义要去掉的前缀
            // 检查原始字符串是否以指定前缀开始
            if (locate.startsWith(prefix)) {
                // 使用substring去掉前缀
                String result = locate.substring(prefix.length());
                ObjectStat objectStat = minioClient.statObject(bucketName, result);
                long size = objectStat.length();
                return DataSizeUtil.format(size);
            }
            else{
                return null;
            }

        }catch (Exception e){
            log.info("minio get Bucket error");
            e.printStackTrace();
            throw new RuntimeException("获取失败");
        }
    }





    /**
     * 获取用户容量还有多少
     * @param bucketName
     * @param userId
     * @param prefix
     * @return
     * @throws Exception
     */
    public String getUserSize(String bucketName, Long userId, String prefix, Boolean vip) throws Exception {
        try {
            Iterable<Result<Item>> itemList = minioClient.listObjects(bucketName, userId.toString());
            long totalSize = 0;

            // Iterate over the results and calculate the total size
            Iterator<Result<Item>> iterator = itemList.iterator();
            while (iterator.hasNext()) {
                Result<Item> result = iterator.next();
                Item item = result.get();
                log.info("item.size():{}",item.size());

                // Check for potential overflow before accumulating the size
                if (Long.MAX_VALUE - item.size() < totalSize) {
                    throw new ArithmeticException("Size calculation overflow");
                }

                // Accumulate the size of each object
                totalSize += item.size();
            }

            if (vip) {
                // For VIP, calculate remaining space (20 GB - totalSize)
                return DataSizeUtil.format(totalSize);
            } else {
                // For non-VIP, calculate remaining space (5 GB - totalSize)
                return DataSizeUtil.format(totalSize);
            }

        } catch (Exception e) {
            log.info("MinIO get Bucket error");
            e.printStackTrace();
            throw new RuntimeException("获取失败");
        }
    }

    private String formatSize(long size) {
        String[] units = {"B", "KB", "MB", "GB", "TB"};
        int unitIndex = 0;
        double sizeInDouble = size;

        while (sizeInDouble >= 1024 && unitIndex < units.length - 1) {
            sizeInDouble /= 1024;
            unitIndex++;
        }

        DecimalFormat df = new DecimalFormat("#.##");
        return df.format(sizeInDouble) + " " + units[unitIndex];
    }


    /**
     * 删除存储bucket
     * @param bucketName 存储bucket名称，必填
     * @return Boolean-
     */
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            log.error("minio remove Bucket error.",e);
            e.printStackTrace();
            return false;
        }
        return true;
    }
 
    /**
     * 将本地文件上传到minio
     * @param filePath      本地文件路径
     * @param bucket        桶
     * @param objectName    对象名称
     */
    private void uploadToMinio(String filePath, String bucket, String objectName) {
        String contentType = objectName.split("\\.")[1];
        try {
            minioClient.uploadObject(UploadObjectArgs
                    .builder()
                    .bucket(bucket)
                    .object(objectName)
                    .filename(filePath)
                    .contentType(contentType)
                    .build());
        } catch (Exception e) {
            log.error("上传到文件系统出错");
        }
    }
 
    /**
     * 文件上传(根据本地文件)，以日期为格式
     * @param bucketName
     * @param prefix 前缀
     * @param fileName 本地文件全路径 D:/xx/xx.text
     * @return
     */
    public String upload(String bucketName, String prefix, String fileName) {
        //判断并创建Bucket
        bucketName = existBucket(bucketName);
        String uuid = UUID.randomUUID().toString().replace("-","");
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        String format = dateFormat.format(new Date());
        StringBuilder stringBuilder = new StringBuilder();
        if (StringUtils.isNotBlank(prefix)) {
            stringBuilder.append(prefix).append(separator);
        }
        String suffix = fileName.split("\\.")[1];
        stringBuilder.append(format).append(separator).append(uuid).append(suffix);
        try {
            // 上传到minio服务器
            minioClient.uploadObject(UploadObjectArgs.builder()
                    .bucket(bucketName)
                    .filename(fileName)
                    .object(stringBuilder.toString())
                    .build());
            return minIOConfigProperties.getReadPath() + separator + minIOConfigProperties.getBucket() +
                    separator +
                    stringBuilder.toString();
        } catch (Exception e) {
            log.error("minio put file error.",e);
            throw new RuntimeException("上传文件失败");
        }
    }
 
    /**
     * 文件上传(根据流),文件路径以日期为格式
     * @param bucketName
     * @param prefix 前缀
     * @param file
     * @return
     */
    public String upload(String bucketName, String prefix, MultipartFile file) {
        //判断并创建Bucket
        bucketName = existBucket(bucketName);
        String filePath = builderFilePath(prefix, file);
        try {
            InputStream inputStream = file.getInputStream();
            // 上传到minio服务器
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(filePath)
                    .stream(inputStream, inputStream.available(), -1)
                    .build());
            return minIOConfigProperties.getReadPath() + separator + minIOConfigProperties.getBucket() +
                    separator +
                    filePath;
        } catch (Exception e) {
            log.error("minio put file error.",e);
            throw new RuntimeException("上传文件失败");
        }
    }
 
    /**
     *  上传图片文件
     * @param bucketName  bucket名称，为空时默认yml配置
     * @param prefix  文件前缀
     * @param multipartFile  文件
     * @return  文件全路径
     */
    public String uploadImgFile(String bucketName, String prefix, MultipartFile multipartFile,String fileName) {
        //判断并创建Bucket
        bucketName = existBucket(bucketName);
        log.info("Minio配置类：{}",multipartFile);
        //构建文件存储路径
        String filePath = builderFilePath(prefix, multipartFile);
        log.info("minIOConfigProperties.getAccessKey():{}",minIOConfigProperties.getAccessKey());
        log.info("minIOConfigProperties.getBucket():{}",minIOConfigProperties.getBucket());
        log.info("minIOConfigProperties.getEndpoint():{}",minIOConfigProperties.getEndpoint());
        log.info("minIOConfigProperties.getReadPath():{}",minIOConfigProperties.getReadPath());
        log.info("minIOConfigProperties.getSecretKey():{}",minIOConfigProperties.getSecretKey());
        try {
            InputStream inputStream = multipartFile.getInputStream();
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .object(filePath)
                    .contentType("image/jpg")
                    .bucket(bucketName)
                    .stream(inputStream,inputStream.available(),-1)
                    .build();
            minioClient.putObject(putObjectArgs);

            return  separator + minIOConfigProperties.getBucket() +
                    separator +
                    filePath;
        }catch (Exception ex){
            log.error("minio put image file error.",ex);
            throw new RuntimeException("上传文件失败");
        }
    }









 
    /**
     * 下载文件
     * @param bucketName 必填
     * @param pathUrl  文件全路径
     * @return  文件流
     */
    public byte[] downLoadFile(String bucketName, String pathUrl)  {
        String key = pathUrl.replace(minIOConfigProperties.getEndpoint()+"/","");
        int index = key.indexOf(separator);
        String bucket = key.substring(0,index);
        String filePath = key.substring(index+1);
        InputStream inputStream = null;
        try {
            inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(filePath).build());
        } catch (Exception e) {
            log.error("minio down file error.  pathUrl:{}",pathUrl);
            e.printStackTrace();
        }
 
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while (true) {
            try {
                if (!((rc = inputStream.read(buff, 0, 100)) > 0)) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
            byteArrayOutputStream.write(buff, 0, rc);
        }
        return byteArrayOutputStream.toByteArray();
    }
 
    /**
     *
     * @param bucketName
     * @param folderPath 分片文件路径
     * @param chunkTotal
     * @param fileName 合并后的文件名
     * @return
     */
    public boolean mergeChunkFiles(String fileMd5, String bucketName, String folderPath, int chunkTotal, String fileName) {
        List<ComposeSource> sources = Stream.iterate(0, i -> i++).limit(chunkTotal).map(i -> ComposeSource
                .builder()
                .bucket(minIOConfigProperties.getBucket())
                .object(folderPath + i).build()).collect(Collectors.toList());
 
        // 合并后文件的名
        String extension = fileName.substring(fileName.lastIndexOf("."));
        String objectName = getFilePathByMd5(fileMd5, extension);
        //指定合并后的objectName等信息
        ComposeObjectArgs composeObjectArgs = ComposeObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .sources(sources)
                .build();
        //合并文件,单个分片文件大小必须为5m
        try {
            minioClient.composeObject(composeObjectArgs);
 
        } catch (Exception e) {
            e.printStackTrace();
            log.error("合并文件出错了，bucket:{},objectName:{},错误信息:{}",minIOConfigProperties.getBucket(), objectName, e.getMessage());
            return false;
        }
        return true;
    }
 
    /**
     * 删除文件
     * @param bucketName 存储bucket名称，必填
     * @param pathUrl  文件全路径
     */
    public boolean deleteFile(String bucketName, String pathUrl) {
        String key = pathUrl.replace(minIOConfigProperties.getEndpoint()+"/","");
        int index = key.indexOf(separator);
        String bucket = key.substring(0,index);
        String filePath = key.substring(index+1);
        // 删除Objects
        RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder().bucket(bucketName).object(filePath).build();
        try {
            minioClient.removeObject(removeObjectArgs);
        } catch (Exception e) {
            log.error("minio remove file error.  pathUrl:{}",pathUrl);
            e.printStackTrace();
            return false;
        }
        return true;
    }
 
    /**
     * 批量删除文件对象
     * @param bucketName 存储bucket名称，必填
     * @param objects 对象名称集合
     */
    public boolean removeObjects(String bucketName, List<String> objects) {
        Map<String,String > resultMap = new HashMap<>();
        List<DeleteObject> dos = objects.stream().map(e -> new DeleteObject(minIOConfigProperties.getReadPath()+e)).collect(Collectors.toList());
        try {
            minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(dos).build());
 
        }catch (Exception e){
            log.error("minio remove file error.  objects:{}",objects);
            return false;
        }
        return true;
    }
 
    /**
     * 文件存储路径构建 yyyy/mm/dd/uuid.jpg
     * @param prefix
     * @param multipartFile
     * @return
     */
    public String builderFilePath(String prefix, MultipartFile multipartFile) {
        String filename = multipartFile.getOriginalFilename();
        assert filename != null;
        String suffix = filename.split("\\.")[1];
        String uuid = UUID.randomUUID().toString().replace("-","");
        StringBuilder stringBuilder = new StringBuilder(50);
        if(StringUtils.isNotBlank(prefix)){
            stringBuilder.append(prefix).append(separator);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String todayStr = sdf.format(new Date());
        stringBuilder.append(todayStr).append(separator).append(uuid);
        stringBuilder.append(".").append(suffix);
        return stringBuilder.toString();
    }
 
    /**
     * 合并后完整视频路径
     * @param fileMd5
     * @param fileExt
     * @return
     */
    private String getFilePathByMd5(String fileMd5, String fileExt) {
        return fileMd5.substring(0, 1) + "/" + fileMd5.substring(1, 2) + "/" + fileMd5 + "/" + fileMd5 + fileExt;
    }
}